package com.birboot.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    //请求相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本
    //消息头相关信息 key:消息头名字     value:消息头对应的值
    private Map<String, String> map = new HashMap<>();


    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //解析请求行
        parsRequestLine();
        //解析消息头
        parseHeaders();
        //解析消息正文
        parseContent();
        }
        //解析请求行
        private void parsRequestLine() throws IOException {
            //1.1解析请求
            String line = readLine();
            System.out.print("请求行：" + line);

            String[] a = line.split("\\s");
            method = a[0];
            uri = a[1];
            protocol = a[2];
            System.out.println("");
            System.out.println("method:" + method);
            System.out.println("uri:" + uri);
            System.out.println("protocol:" + protocol);

        }
        //解析消息头
        private void parseHeaders() throws IOException {
            while (true) {
               String line = readLine();
                if ((line.isEmpty())) {
                    break;
                }
                System.out.println("消息头：" + line);
                String[] s = line.split(":\\s");
                map.put(s[0], s[1]);

                String tou = s[0];
                String tou1 = s[1];
                System.out.println(tou + "," + tou1);
            }
            System.out.println("map:"+map);
        }
         //解析消息正文
        private void parseContent(){}

        private String readLine () throws IOException {
            //
            InputStream is = socket.getInputStream();
            int d;
            char pre = 'a', cur = 'a';//pre代表上次读取的字符，cur代表这次读取的字符
            StringBuilder builder = new StringBuilder();//保存读取后的所有字符
            while ((d = is.read()) != -1) {
                cur = (char) d;//本次读取字符
                if (pre == 13 && cur == 10) {//判断是否为回车和换行
                    break;
                }
                builder.append(cur);//将本次读取的字符拼接
                pre = cur;//把本次读取的字符给到pre
            }
            //将获取到的信息转换为字符串型，并去除首尾空白符
            return builder.toString().trim();
    }
    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getMap(String name) {
        return map.get(name);
    }
}

